import json

import httpx
from fastapi import APIRouter, Form
from re_common.baselibrary.tools.all_requests.requests_request import RequestsRequest

from app.allsubdb.globalmodel import RequestModel
from app.allsubdb.wanfangqk.models import bools_string
from app.core.return_info import ReturnInfo, SUCCESS, FAILED

router = APIRouter()


@router.post("/down/wanfangref_old")
async def down_old_ref(*, proxy: str = Form(None), rawid: str = Form(...), page: str = Form(...)):
    """
    老网页的ref
    :param proxy:
    :param rawid:
    :param page:
    :return:
    """
    return_info = ReturnInfo()
    url = "http://d.old.wanfangdata.com.cn/CiteRelation/Ref"
    headers = {
        "Accept": "*/*",
        "Host": "d.old.wanfangdata.com.cn",
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36"
    }
    params = {
        "id": rawid,
        "page": page
    }
    Proxiesss = None
    if proxy:
        Proxiesss = {
            'http': "http://" + proxy,
            'https': "http://" + proxy
        }
    r = None
    async with httpx.AsyncClient(proxies=Proxiesss) as client:
        r = await client.get(url, params=params, headers=headers)
        print(r.url)
    if r is not None:
        if r.status_code == 200:
            return_info.status = SUCCESS
            return_info.data = {"html": r.text}
        else:
            return_info.msg_code = r.status_code
            return_info.msg = "状态码错误:" + str(r.status_code)
            return_info.data = {"rawid": rawid, "page": page, "proxy": proxy}
    else:
        return_info.msg = "请求错误，没有返回Response"
        return_info.data = {"rawid": rawid, "page": page, "proxy": proxy}
    return return_info.todict()


@router.post("/down/wanfangref")
async def down_ref(*, proxy: str = Form(None), rawid: str = Form(...), page: str = Form(...)):
    """
    下载ref
    :param proxy:
    :param rawid:
    :param page:
    :return:
    """
    return_info = ReturnInfo()
    url = "http://d.wanfangdata.com.cn/Detail/Reference"
    headers = {
        'Accept': 'application/json, text/plain, */*',
        'Accept-Encoding': 'gzip, deflate',
        'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
        'Host': 'd.wanfangdata.com.cn',
        'Referer': 'http://d.wanfangdata.com.cn/periodical/spgy201909082',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36',
    }
    headers['Referer'] = 'http://d.wanfangdata.com.cn/periodical/%s' % rawid
    params = {
        'Id': str(rawid),
        'PageNum': str(page),
        "ReferenceType": "Reference"
    }
    data = json.dumps(params)
    Proxiesss = None
    if proxy:
        Proxiesss = {
            'http': "http://" + proxy,
            'https': "http://" + proxy
        }
    r = None
    async with httpx.AsyncClient(proxies=Proxiesss) as client:
        r = await client.post(url, data=data, headers=headers)
        print(r.url)
    if r is not None:
        if r.status_code == 200:
            result = json.loads(r.text)
            return_info.status = SUCCESS
            return_info.data = result
        else:
            return_info.msg_code = r.status_code
            return_info.msg = "状态码错误:" + str(r.status_code)
            return_info.data = {"rawid": rawid, "page": page, "proxy": proxy}
    else:
        return_info.msg = "请求错误，没有返回Response"
        return_info.data = {"rawid": rawid, "page": page, "proxy": proxy}
    return return_info.todict()


@router.post("/down/a_z/wanfangqklist")
async def down_wanfangqklist(pageNum: int, ch):
    """
    以a到z 请求json 获取列表
    :param proxy:
    :param rawid:
    :param page:
    :return:
    """
    return_info = ReturnInfo()
    url = r'http://c.wanfangdata.com.cn/Category/Magazine/search'
    headers = {
        'Accept': 'application/json, text/plain, */*',
        'Host': 'c.wanfangdata.com.cn',
        'Content-Type': 'application/json;charset=UTF-8',
        'Referer': 'http://c.wanfangdata.com.cn/periodical',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0',
    }
    form = {
        "class_code": "",
        "core_periodical": [],
        "highlight_field": "",
        "pinyin_title": ["A"],
        "publish_status": "",
        "publishing_period": [],
        "query": [],
        "return_fields": [],
        "rows": 50,
        "sort_field": {"sort_field": "ImpactFactor"},
        "sponsor_region": [],
        "start": 0
    }
    form['start'] = (pageNum - 1) * 50
    form["pinyin_title"] = [ch]
    rrq = RequestsRequest()
    rrq.set_header(headers).set_url(url) \
        .set_timeout((10, 30)).set_marks(["value", "total"]) \
        .set_data(json.dumps(form)) \
        .set_middler_list([rrq.status_code_middlerwares, rrq.marks_middlerwares, rrq.is_json_middlerwares])
    rrq.builder()
    bools, dicts = rrq.run("post")
    print(bools)
    print(dicts)
    return_info.status = bools_string(bools)
    return_info.msg_code = dicts["code"]
    return_info.msg = dicts["msg"]
    return_info.data = {"jsons": rrq.html}
    return return_info.todict()
